package com.swak.consistency.tcc.resolve;

import java.util.Map;

import org.apache.dubbo.rpc.RpcContext;

import com.swak.consistency.core.attribute.ConsistencyAttribute;
import com.swak.consistency.tcc.context.TccContext;
import com.swak.utils.JsonMapper;

/**
 * Dubbo 获取数据的方式
 * 
 * @author DELL
 */
public class DubboTccContextResolver extends TccContextResolver {

	String CONTEXT_ATTR = "_SWAK_CC_KEY";

	@Override
	public TccContext acquire(ConsistencyAttribute attribute) {
		Map<String, Object> attachments = RpcContext.getContext().getObjectAttachments();
		if (attachments != null && attachments.containsKey(CONTEXT_ATTR)) {
			String attrJson = (String) attachments.get(CONTEXT_ATTR);
			TransAttr attr = JsonMapper.fromJson(attrJson, TransAttr.class);
			if (attr != null) {
				return new TccContext().setTransId(attr.getTransId()).setPhase(attr.getPhase()).as();
			}
		}
		return null;
	}

	@Override
	public void transmit(TccContext context) {
		TransAttr attr = new TransAttr().setTransId(context.getTransId()).setPhase(context.getPhase());
		RpcContext.getContext().setAttachment(CONTEXT_ATTR, JsonMapper.toJson(attr));
	}
}
